package com.jnchen.jwt.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jnchen.jwt.api.JwtInterface;
import com.jnchen.jwt.entity.User;
import com.jnchen.jwt.util.RsaUtil;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;

/**
 * Auth0 java jwt 实现
 *
 * @author jnchen
 * @date 2020/10/30 09:47
 */
public class Auth0JwtImpl implements JwtInterface {

    private static final Algorithm ALGORITHM;

    static {
        KeyPair pair = RsaUtil.getRsaKey();
        ALGORITHM = Algorithm.RSA256((RSAPublicKey) pair.getPublic(), (RSAPrivateKey) pair.getPrivate());
    }

    @Override
    public String createJwt(User user, long expireIn) {
        return JWT.create().withClaim("id", user.getId()).withClaim("name", user.getName())
                .withClaim("operations", user.getOperations())
                .withExpiresAt(new Date(System.currentTimeMillis() + expireIn))
                .sign(ALGORITHM);
    }


    @Override
    public User parseJwt(String token) {
        JWTVerifier verifier = JWT.require(ALGORITHM).build();
        DecodedJWT jwt = verifier.verify(token);
        User user = new User();
        user.setId(jwt.getClaim("id").asInt());
        user.setName(jwt.getClaim("name").asString());
        user.setOperations(jwt.getClaim("operations").asList(String.class));
        return user;
    }

    @Override
    public boolean checkJwt(String token) {
        try {
            JWT.require(ALGORITHM).build().verify(token);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
